﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Elight.Entity;
using Elight.Service.Interfaces;
using Elight.Repository.Interfaces;

namespace Elight.Service
{
    public partial class AccessService : BaseService<Sys_Access>, IAccessService
    {
        private readonly IUserRoleRepository _userRoleRepository;
        private readonly IRoleAccessRepository _roleAccessRepository;
        private readonly IAccessRepository _accessRepository;

        public AccessService(
            IUserRoleRepository userRoleRepository,
            IRoleAccessRepository roleAccessRepository,
            IAccessRepository accessRepository)
        {
            _userRoleRepository = userRoleRepository;
            _roleAccessRepository = roleAccessRepository;
            _accessRepository = accessRepository;
        }

        public IEnumerable<Sys_Access> GetList(int userId)
        {
            //a.根据用户ID查询角色ID集合。
            var listRoleIds = _userRoleRepository.GetList(userId).Select(c => c.RoleId).ToArray();
            //b.根据角色ID查询权限ID集合。
            var listAccessIds = _roleAccessRepository.GetList(listRoleIds).Select(c => c.AccessId).ToArray();
            //c.根据权限ID集合查询权限实体集合。
            return _accessRepository.GetList(listAccessIds).Where(c => c.IsEnable);
        }

        public bool Validate(int userId, string requestPath, string requestMethod)
        {
            var listAccess = GetList(userId);

            foreach (Sys_Access access in listAccess)
            {
                if (access.Path.ToLower() == requestPath.ToLower() &&
                    access.Method.ToUpper() == requestMethod.ToUpper())
                {
                    return true;
                }
            }
            return false;
        }
    }
}
